package com.ruoyi.cloudpc.service.impl;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.cloudpc.utils.SequenceGenerator;
import com.ruoyi.cloudpc.domain.CloudDevice;
import com.ruoyi.cloudpc.domain.CloudOrder;
import com.ruoyi.cloudpc.domain.CloudProduct;
import com.ruoyi.cloudpc.domain.CloudPromotion;
import com.ruoyi.cloudpc.enums.OrderStatusEnum;
import com.ruoyi.cloudpc.mapper.CloudOrderMapper;
import com.ruoyi.cloudpc.service.CloudPromotionService;
import com.ruoyi.cloudpc.service.ICloudDeviceService;
import com.ruoyi.cloudpc.service.ICloudOrderService;
import com.ruoyi.cloudpc.service.ICloudProductService;
import com.ruoyi.common.annotation.DataScope;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.service.ISysConfigService;
import com.ruoyi.system.service.ISysUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.List;

/**
 * 订单信息Service业务层处理
 *
 * @author Ten
 * @date 2025-09-13
 */
@Slf4j
@Service
public class CloudOrderServiceImpl implements ICloudOrderService {
    @Autowired
    private CloudOrderMapper cloudOrderMapper;

    @Autowired
    private ICloudProductService cloudProductService;

    @Autowired
    private CloudPromotionService cloudPromotionService;

    @Autowired
    private ISysUserService userService;
    @Autowired
    private ISysConfigService configService;
    @Autowired
    private SequenceGenerator sequenceGenerator;
    @Autowired
    private ICloudDeviceService deviceService;

    /**
     * 查询订单信息
     *
     * @param id 订单信息主键
     * @return 订单信息
     */
    @Override
    public CloudOrder selectCloudOrderById(Long id) {
        return cloudOrderMapper.selectCloudOrderById(id);
    }

    /**
     * 查询订单信息列表
     *
     * @param cloudOrder 订单信息
     * @return 订单信息
     */
    @DataScope(userAlias = "u", permission = "common")
    @Override
    public List<CloudOrder> selectCloudOrderList(CloudOrder cloudOrder) {
        List<CloudOrder> cloudOrders = cloudOrderMapper.selectCloudOrderList(cloudOrder);
        for (CloudOrder order : cloudOrders) {
//            order.setDevice(deviceService.selectCloudDeviceByOrderId(order.getId()));
            order.setDevice(queryByOrder(order));
            if (StringUtils.isNotBlank(order.getRemark())) {
                CloudProduct cloudProduct = JSONObject.parseObject(order.getRemark(), CloudProduct.class);
                order.setProductDesc(
                        StringUtils.format("{}·{}·{}·{}",
                            cloudProduct.getCores(),
                            cloudProduct.getMemory(),
                            cloudProduct.getDisk(),
                            formatDuration(order.getDuration())
                        )
                );
//                order.setProductDesc(
//                        StringUtils.format("{}核{}G·{}存储·{}",
//                            cloudProduct.getCores(),
//                            cloudProduct.getMemory(),
//                            cloudProduct.getDisk(),
//                            formatDuration(order.getDuration())
//                        )
//                );
            }
        }
        return cloudOrders;
    }

    /**
     * 根据订单查询设备信息
     * @param order 订单
     * @return
     */
    private CloudDevice queryByOrder(CloudOrder order){
        if (order.getRenewId() != null) {
            CloudOrder renewOrder = this.cloudOrderMapper.selectCloudOrderById(order.getRenewId());
            CloudDevice cloudDevice = deviceService.selectCloudDeviceByOrderId(renewOrder.getId());
            if (cloudDevice != null) {
                return cloudDevice;
            } else {
                queryByOrder(renewOrder);
            }
        }
        return deviceService.selectCloudDeviceByOrderId(order.getId());
    }

    private String formatDuration(Long duration) {
        // 天 月
        if (duration <= 7) {
            return StringUtils.format("{}天", duration);
        } else {
            return StringUtils.format("{}月", duration / 30);
        }
    }

    /**
     * 新增订单信息
     * 触发时机：付款成功后，创建订单。这里要区分是新增订单，还是续费订单
     *
     * @param cloudOrder 订单信息
     * @return 结果
     */
    @Transactional
    @Override
    public int insertCloudOrder(CloudOrder cloudOrder) {

        cloudOrder.setOrderNo(sequenceGenerator.generateNumber());

//        // 新建订单默认值为待付款
//        cloudOrder.setStatus(OrderStatusEnum.ORDER_STATUS_DFK.getStatus());
        // 新建订单默认值为待开通
        cloudOrder.setStatus(OrderStatusEnum.ORDER_STATUS_DKT.getStatus());

        cloudOrder.setCreateByAndTime();

        CloudProduct cloudProduct = cloudProductService.selectCloudProductById(cloudOrder.getProductId());
        cloudOrder.setRemark(JSON.toJSONString(cloudProduct));
        //　单价、数量、总金额这些由前端带过来
        int result = cloudOrderMapper.insertCloudOrder(cloudOrder);

        // 当前登录用户如果有推广人，需要存入推广信息
        SysUser sysUser = userService.selectUserById(SecurityUtils.getUserId());
        if (StringUtils.isNotBlank(sysUser.getPromoter())) {
            if ("undefined".equals(sysUser.getPromoter())) {
                log.error("未能正确获取到推广人信息，请联系客服处理(下单时)！ 入参信息：{}", JSONObject.toJSONString(cloudOrder));
                throw new ServiceException("未能正确获取到推广人信息，请联系客服处理！");
            }

            // 抽佣比例
            String commissionRateStr = configService.selectConfigByKey("CommissionRate");
            BigDecimal commissionRate = new BigDecimal(commissionRateStr);

            CloudPromotion cloudPromotion = new CloudPromotion();
            cloudPromotion.setFromUserName(sysUser.getPromoter());
            cloudPromotion.setToUserName(SecurityUtils.getUsername());

            cloudPromotion.setCreateByAndTime();
            cloudPromotion.setOrderId(cloudOrder.getId());
            cloudPromotion.setCommissionRate(commissionRate);
            BigDecimal totalAmount = cloudOrder.getTotalAmount();
            // 订单总额需要减掉附加费
            BigDecimal surcharge = cloudOrder.getSurcharge();
            /*
                双佣金模式
                    用户下单选附加费佣金就是附加费
                    用户下单没选附加费就是原来的
             */
            if (surcharge == null || surcharge.compareTo(BigDecimal.ZERO) == 0) {
                surcharge = BigDecimal.ZERO;
                cloudPromotion.setCommissionAmount(commissionRate.multiply(totalAmount.subtract(surcharge)));
            } else {
                cloudPromotion.setCommissionAmount(surcharge);
            }

            int insertCloudPromotion = cloudPromotionService.insertCloudPromotion(cloudPromotion);
            if (insertCloudPromotion == 0) {
                throw new RuntimeException("抽佣信息处理失败");
            }
        }

        return result;
    }

    /**
     * 修改订单信息
     *
     * @param cloudOrder 订单信息
     * @return 结果
     */
    @Override
    public int updateCloudOrder(CloudOrder cloudOrder) {
        cloudOrder.setUpdateByAndTime();
        return cloudOrderMapper.updateCloudOrder(cloudOrder);
    }

    /**
     * 批量删除订单信息
     *
     * @param ids 需要删除的订单信息主键
     * @return 结果
     */
    @Override
    public int deleteCloudOrderByIds(Long[] ids) {
        return cloudOrderMapper.deleteCloudOrderByIds(ids);
    }

    /**
     * 删除订单信息信息
     *
     * @param id 订单信息主键
     * @return 结果
     */
    @Override
    public int deleteCloudOrderById(Long id) {
        return cloudOrderMapper.deleteCloudOrderById(id);
    }

    /**
     * 支付订单
     *
     * @param id 订单id
     * @return 结果
     */
    @Override
    public int pay(Long id) {
        CloudOrder cloudOrder = selectCloudOrderById(id);
        Integer currentStatus = cloudOrder.getStatus();
        int nextStats = OrderStatusEnum.nextOrderStatus(currentStatus).getStatus();
        cloudOrder.setStatus(nextStats);
        return cloudOrderMapper.updateCloudOrder(cloudOrder);
    }

    /**
     * 订单开通
     *
     * @param device 订单id
     * @return 结果
     */
    @Transactional
    @Override
    public int open(CloudDevice device) {
        CloudOrder cloudOrder = selectCloudOrderById(device.getOrderId());

        Integer currentStatus = cloudOrder.getStatus();
        Long renewId = cloudOrder.getRenewId();
//        if (renewId != null) {
//            // 续费情况下，订单状态
//            int nextStats = OrderStatusEnum.nextOrderStatus(currentStatus).getStatus();
//            cloudOrder.setStatus(nextStats);
//        }
        cloudOrder.setStatus(OrderStatusEnum.ORDER_STATUS_YWC.getStatus());

        int updateCloudOrder = cloudOrderMapper.updateCloudOrder(cloudOrder);

        // 续费的订单id，有则代表为续费顶顶那，无则代表正常订单
        if (renewId != null) {
            device.setOrderId(renewId);
            int updateCloudDevice = deviceService.updateCloudDevice(device);
            if (updateCloudDevice == 0) {
                throw new RuntimeException("续费开通失败");
            }
        } else {
            // 保存关联设备信息
            int insertCloudDevice = deviceService.insertCloudDevice(device);
            if (insertCloudDevice == 0) {
                throw new RuntimeException("开通失败");
            }
        }
        return updateCloudOrder;
    }

    @Override
    public List<CloudDevice> myDeviceList(CloudDevice cloudDevice) {
        cloudDevice.setCreateBy(SecurityUtils.getUsername());
        List<CloudDevice> cloudDevices = deviceService.myDeviceList(cloudDevice);
        // 将订单信息放进来，用来作商品信息的展示
        for (CloudDevice device : cloudDevices) {
            CloudOrder order = cloudOrderMapper.selectCloudOrderById(device.getOrderId());
            if (StringUtils.isNotBlank(order.getRemark())) {
                CloudProduct cloudProduct = JSONObject.parseObject(order.getRemark(), CloudProduct.class);
                order.setProductDesc(
                        StringUtils.format("{}·{}·{}·{}",
                                cloudProduct.getCores(),
                                cloudProduct.getMemory(),
                                cloudProduct.getDisk(),
                                formatDuration(order.getDuration())
                        )
                );
            }
            device.setOrder(order);
        }
        return cloudDevices;
    }

    @Override
    public int updateDeviceId(CloudDevice device) {
        CloudOrder cloudOrder = selectCloudOrderById(device.getOrderId());

        Long renewId = cloudOrder.getRenewId();

        // 续费的订单id，有则代表为续费顶顶那，无则代表正常订单
        if (renewId != null) {
            device.setOrderId(renewId);
        }
        return deviceService.updateDeviceId(device);
    }
}
